

/**
 * @return bool true if column is visible after call.
 */
window.babAddonWidgets.tableview_setColumnVisible = function(tableview, cellIndex, visibility) {

	var tab = tableview.getElementsByTagName('TABLE')[0];
	
	var colStart = 0;
	for (var c = 0; c < cellIndex; c++) {
		colStart += tab.rows[0].cells[c].colSpan;
	}
	
	var nbRows = tab.rows.length;
	var tdColSpan = tab.rows[0].cells[cellIndex].colSpan;

	var visible = jQuery(tab.rows[0].cells[colStart]).is(':visible');
	if (visibility === 'visible') {
		visible = true;
	} else if (visibility === 'hidden') {
		visible = false;
	} else {
		visible = !visible;
	}

	for (var r = 0; r < nbRows; r++) {

		var row = tab.rows[r];
		for (c = 0; c < tdColSpan; c += row.cells[colStart + c].colSpan) {
			if (visibility === 'visible') {
				jQuery(row.cells[colStart + c]).fadeIn('slow');
			} else if (visibility === 'hidden') {
				jQuery(row.cells[colStart + c]).fadeOut('fast');
			} else {
				jQuery(row.cells[colStart + c]).fadeToggle('slow');
			}
		}
	}
	return visible;
}


window.babAddonWidgets.tableview_init = function(domNode) {


	jQuery(domNode).find('.widget-tableview').each(function () {
			
		var tableView = this;
			
		jQuery(this).find('.widget-table-header .widget-tableview-column-menu a.column-toggle').click(function () {
			var meta = window.babAddonWidgets.getMetadata(this.id);
			var columnName = meta.columnName;
			var visible = window.babAddonWidgets.tableview_setColumnVisible(tableView, meta.cellIndex, 'toggle');
			jQuery.ajax({
				url: '',
				data: 'tg=addon/widgets/configurationstorage&key='+encodeURIComponent(tableView.id + '/' + 'columns/' + columnName) + '&value=' + (visible ? '1' : '0')
			});

			jQuery(this).find('.widget-icon').toggleClass('actions-dialog-ok');
			return false;
		});

		jQuery(this).find('.widget-table-header .widget-tableview-column-menu a.columns-reset').click(function () {
			jQuery.ajax({
				url: '',
				data: 'tg=addon/widgets/configurationstorage&idx=delete&path='+encodeURIComponent(tableView.id + '/' + 'columns')
			});
		});

	}); 
	
	
//	jQuery(domNode).find('.widget-suggestlineedit').keyup(function(event){
//		window.babAddonWidgets.suggestlineedit_setValue(jQuery(event.target));
//	});
	
};





window.bab.addInitFunction(window.babAddonWidgets.tableview_init);

